/* eslint-disable */
import http from './httpWeb';
import { boolDk, os, isFunction } from './tool';

//使用iFrame去请求url代替location.href，防止iOS端过于密集的调用mobilecall导致后发起的请求被忽略和app未安装通用链直接报错
export const loadURL = url => {
    let iFrame = document.createElement("iframe");
    iFrame.setAttribute("src", url);
    iFrame.setAttribute("style", "display:none;");
    iFrame.setAttribute("height", "0px");
    iFrame.setAttribute("width", "0px");
    iFrame.setAttribute("frameborder", "0");
    document.body.appendChild(iFrame);
    // 发起请求后这个 iFrame 就没用了，所以把它从 dom 上移除掉
    iFrame.parentNode.removeChild(iFrame);
    iFrame = null;
};
/**
 *
 * @param {object} optionsObj
 * @param {(string|number)} [optionsObj.cmd]
 * @param {object} [optionsObj.data]
 * @param {string} [optionsObj.callbackName]
 * @param {string} [optionsObj.success]
 * @param {function} [optionsObj.callback]
 */
export default function dkMobileCall (optionsObj) {
    let options = Object.assign(
        {
            cmd: "",
            data: {},
            callbackName: "",
            success: ""
        },
        optionsObj
    );
    let sign = http.sign;
    if (options.callbackName && isFunction(options.success)) {
        //window[options.callback]
        if (!window.kgMobileCall) {
            window.kgMobileCall = {};
        }
        window.kgMobileCall[options.callbackName.split(".").pop()] = options.success;
    }
    if (boolDk) {
        if (options && options.sign) {
            sign = options.sign;
        }
        // var data = '{"cmd":"'+options.cmd+'","sign":"'+sign+'","jsonStr":'+JSON.stringify(options.data)+',"callback":"'+options.callbackName+'"}';

        let oData = {};
        oData.cmd = options.cmd;
        oData.sign = sign;
        oData.jsonStr = options.data;

        if (options.callbackName) {
            oData.callback = options.callbackName;
        } else if (options.callback) {
            const callbackname = `_fxwebviewjsfunc_${new Date().getTime()}`;
            //alert("正在设置window." + callbackname);
            window[callbackname] = (...args) => {
                options.callback(...args);
                delete window[callbackname];
            };
            oData.callback = callbackname;
        }

        let data = JSON.stringify(oData);
        if (os.ios) {
            let iosApi = `fanxing2://send.message/?${data}`;
            loadURL(iosApi);
        } else if (window.external && window.external.callFanxing) {
          console.log(data)
            window.external.callFanxing(data);
        } else {
            alert("网络有点不给力哦!重新进入页面再点击试试吧!");
        }
    }
}
